package com.specialtreasure.freightdepot.activity;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Environment;
import android.os.Process;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.app.core.activity.BaseNewActivity;
import com.app.core.config.Constants;
import com.app.core.config.HttpApi;
import com.app.core.config.MyApp;
import com.app.core.util.ApkUtil;
import com.app.core.util.DeviceUtil;
import com.specialtreasure.freightdepot.R;
import com.specialtreasure.freightdepot.model.ClientUpdateInfo;
import com.specialtreasure.freightdepot.model.Login;
import com.vondear.rxtools.RxAppUtils;
import com.yanzhenjie.httpmodule.http.CallServer;
import com.yanzhenjie.httpmodule.http.Result;
import com.yanzhenjie.httpmodule.http.StringRequest;
import com.yanzhenjie.nohttp.Logger;
import com.yanzhenjie.nohttp.RequestMethod;
import com.yanzhenjie.nohttp.rest.CacheMode;
import com.yanzhenjie.nohttp.rest.Response;
import com.yanzhenjie.nohttp.rest.SimpleResponseListener;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;
import com.yanzhenjie.permission.PermissionListener;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.util.List;

/**
 * Created by Administrator on 2017/8/7 0007.
 * 登陆
 */

public class LoginActivity extends BaseNewActivity implements View.OnClickListener {

    public static final String TAG = "LoginActivity";
    private EditText et_username;
    private EditText et_password;
    private CheckBox ck_pwd;
    private Button btn_login;
    private String username, password;
    private TextView tv_tel;
    private TextView tv_time;
    private TextView tv_version;
    private CheckBox ck_autologin;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_login);
        initView();
        setData();
        getPermission();

    }


    private void initView() {
        et_username = (EditText) findViewById(R.id.et_username);
        et_password = (EditText) findViewById(R.id.et_password);
        ck_pwd = (CheckBox) findViewById(R.id.ck_pwd);
        btn_login = (Button) findViewById(R.id.btn_login);

        btn_login.setOnClickListener(this);
        tv_tel = (TextView) findViewById(R.id.tv_tel);
        tv_time = (TextView) findViewById(R.id.tv_time);
        tv_version = (TextView) findViewById(R.id.tv_version);
        ck_autologin = (CheckBox) findViewById(R.id.ck_autologin);
    }


    private void setData() {
        //从缓存中获取数据
        username = MyApp.getInstance().getaCache().getAsString(Constants.USERNAME);
        password = MyApp.getInstance().getaCache().getAsString(Constants.PASSWORD);
        et_username.setText(username);
        et_password.setText(password);

        //记住密码
        if (!TextUtils.isEmpty(password)) {
            ck_pwd.setChecked(true);
        } else {
            ck_pwd.setChecked(false);
        }
        //版本号
//        tv_version.setText("v" + RxAppUtils.getAppVersionName(mContext) + "beta1");
        tv_version.setText(RxAppUtils.getAppVersionName(mContext));

    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_login:
                submit();
                break;
        }
    }

    /**
     * 登陆
     */
    private void submit() {
        // validate
        username = et_username.getText().toString().trim();
        password = et_password.getText().toString().trim();

        if (TextUtils.isEmpty(username)) {
            Toast.makeText(this, "请输入用户名", Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(password)) {
            Toast.makeText(this, "请输入密码", Toast.LENGTH_SHORT).show();
            return;
        }

        showDialog(Constants.LOADING);

        //密码
        MyApp.getInstance().getaCache().put(Constants.USERNAME, username);
        Boolean isCheck = ck_pwd.isChecked();
        if (isCheck) {
            MyApp.getInstance().getaCache().put(Constants.PASSWORD, password);
        } else {
            MyApp.getInstance().getaCache().put(Constants.PASSWORD, "");
        }
        //自动登录
        Boolean isAutoLogin=ck_autologin.isChecked();
        if (isAutoLogin){
            MyApp.getInstance().getSp().setValue(Constants.AUTOLOGIN,true);
        }else {
            MyApp.getInstance().getSp().setValue(Constants.AUTOLOGIN,false);
        }



        getData();
    }

    /**
     * 请求登陆
     */
    private void getData() {
        String url = Constants.HTTP_URL + HttpApi.LOGIN;
        StringRequest request = new StringRequest(url, RequestMethod.POST);
        request.add("username", username);
        request.add("password", password);
        request.add("loginTypeId", 2);
        request.add("hardware", DeviceUtil.getAndroidId(mContext));
        request.setCacheMode(CacheMode.ONLY_REQUEST_NETWORK);

        CallServer.getInstance().request(Constants.ZERO, request, new SimpleResponseListener<Result<String>>() {
            @Override
            public void onSucceed(int what, Response<Result<String>> response) {
                super.onSucceed(what, response);
                closeDialog();
                String result = response.get().getResult();
                Logger.e("请求成功：" + result);
                Login login = JSON.parseObject(result, Login.class);
                if (login != null) {
                    Integer status = login.getStatus();
                    String msg = login.getMsg();
                    if (status != null && status == 0) {
                        MyApp.getInstance().getaCache().remove(Constants.LOGIN);
                        MyApp.getInstance().getaCache().put(Constants.LOGIN, login);
                        intent.setClass(mContext, MainActivity.class);
                        startActivity(intent);
                        finish();
                    } else {
                        Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();
                    }
                }


            }
        });


    }




    /**
     * 多权限申请
     */
    private void getPermission() {
        AndPermission.with(this)
                .permission(Permission.CAMERA, Permission.PHONE, Permission.LOCATION, Permission.STORAGE) // 多个权限组。
                .requestCode(300)
                .callback(new PermissionListener() {
                    @Override
                    public void onSucceed(int requestCode, @NonNull List<String> list) {
                        // TODO do something...
                        if (requestCode == 300) {
//                            AndPermission.defaultSettingDialog(MainActivity.this, 400).show();
                        }
                    }

                    @Override
                    public void onFailed(int requestCode, @NonNull List<String> list) {
                        // TODO 用户没有同意授权，一般弹出Dialog让用户去Setting中授权。
                        if (requestCode == 300) {
                        }
                    }
                })
                .start();
    }

    @Override
    public String getActiviyName() {
        return TAG;
    }
}
